#include <sys.h>

volatile unsigned char flash_flag = 0; 

#define DO_SAVE_INTEGER(p, val) do{\
    int ret = -1;\
    if(*p != val) {\
        *p = val;\
        flash_flag = 1;\
        ret = 1;\
    }\
    return ret;\
}while(0)



int set_val_u8(unsigned char val, unsigned char* p)
{
	DO_SAVE_INTEGER(p, val);
}

int set_val_u16(unsigned short     val, unsigned short* p)
{
	DO_SAVE_INTEGER(p, val);
}

int set_val_u32(unsigned int val, unsigned int* p)
{
	DO_SAVE_INTEGER(p, val);
}

int set_val_array(unsigned char* array, const unsigned char* data, unsigned char len)
{
    int ret = -1;
    if(0 != memcmp(array, data, len)) {
        memcpy(array, data, len);
        ret = 1;
        flash_flag = 1;
    }
    return ret;
}

int str2ip(const char *str, unsigned char *ip, unsigned char len)
{
	char buf[4]={'\0'};
	int tmp;
	int i,j=0,nb=0;
	for(i= 0;i<len && nb<4;i++)									   
	{
		if (str[i]=='\0'||str[i]=='.'||str[i]==':'||j>=4)
		{
			tmp =atoi(buf);
			if (tmp<0||tmp>255){
				return 1;
			}
			ip[nb++]= tmp;	//set val
			memset(buf,0,4);
			j=0;
			continue;
		}
		buf[j]=str[i];	//copy
		j++;
	}
	return 0;
}

int str2mac(const char *str, unsigned char *ip, unsigned char len)
{
	char buf[3]={'\0'};
	int tmp;
	int i,j=0,nb=0;
	for(i= 0;i<len && nb<6;i++)								   
	{
		if (str[i]=='\0'||str[i]==':'||j>=3)
		{
			sscanf(buf, "%x", &tmp);	
			if (tmp<0||tmp>255){
				return -1;
			}
			ip[nb++]= tmp;
			memset(buf,0,sizeof(buf));
			j=0;
			continue;
		}
		buf[j]=str[i];
		j++;
	}
	return 0;
}


int _set_ip(const char* str, unsigned char *cfg) {
    unsigned char ip[4];
    if(str2ip(str, ip, MIN(16, strlen(str)+1))) {
        return -1;
    }
    return set_val_array(cfg, ip, 4);
}

int _set_6bytes_mac(const char* str, unsigned char *cfg) {
    unsigned char mac[6];
    if(str2mac(str, mac, MIN(18, strlen(str)+1))) {
        return -1;
    }
    return set_val_array(cfg, mac, 6);
}







